package com.ywr;

import cn.hutool.core.lang.Assert;
import org.apache.commons.lang.time.DateUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/**
 * @author jm017801
 */
public class RelativeTimeUtil {

    public static Date addDays(Date baseDate, Integer days, DayTypeEnum dayType) {
        Assert.notNull(baseDate);
        Date a24HourDate = DateUtils.addDays(baseDate, days);
        if (Objects.isNull(dayType)) {
            dayType = DayTypeEnum.A24_HOUR;
        }
        switch (dayType) {
            case NORMAL:
                return DateUtils.addDays(Objects.requireNonNull(formatNormalDate(baseDate)), days);
            case A24_HOUR:
            default:
                return a24HourDate;
        }

    }

    /**
     * PIONEER-7747 自然日优惠券，自然日时间根据产品定义，更改为23:59:59
     */
    public static Date addDaysForEndTime(Date baseDate, Integer days, DayTypeEnum dayType) {
        Assert.notNull(baseDate);
        dayType = Optional.ofNullable(dayType).orElse(DayTypeEnum.A24_HOUR);
        switch (dayType) {
            case NORMAL:
                // PIONEER-7747 自然日优惠券，自然日时间根据产品定义，更改为23:59:59
                return DateUtils.addSeconds(DateUtils.addDays(Objects.requireNonNull(formatNormalDate(baseDate)), days), -1);
            case A24_HOUR:
            default:
                return DateUtils.addDays(baseDate, days);
        }

    }


    public static DayTypeEnum dayTypeConverter(Integer typeCode) {
        if (Objects.isNull(typeCode)) {
            return DayTypeEnum.A24_HOUR;
        }
        return EnumCode.encode(DayTypeEnum.class, typeCode).orElse(DayTypeEnum.A24_HOUR);

    }


    private static Date formatNormalDate(Date baseDate) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String s = sdf.format(baseDate);
            return sdf.parse(s);
        } catch (Exception e) {
            return null;
        }

    }
}
